package com.crazymaker.springcloud.base.filter;

import com.alibaba.fastjson.JSON;
import com.crazymaker.springcloud.base.service.UserServiceImpl;
import com.crazymaker.springcloud.common.constants.SessionConstants;
import com.crazymaker.springcloud.common.context.SessionHolder;
import com.crazymaker.springcloud.common.dto.UserDTO;
import com.crazymaker.springcloud.standard.redis.RedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.session.Session;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
public class SessionDataLoadFilter extends OncePerRequestFilter {

    private RedisRepository redisRepository;

    private UserServiceImpl userService;

    public SessionDataLoadFilter(RedisRepository redisRepository, UserServiceImpl userService) {
        this.redisRepository = redisRepository;
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String sid = SessionHolder.getSid();
        HttpSession httpSession = request.getSession();

        if (StringUtils.isBlank(sid) || !sid.equals(httpSession.getId())) {
            sid = httpSession.getId();
            SessionHolder.setSid(sid);
            // 将用户ID和sessionid进行绑定
            redisRepository.setSessionId(SessionHolder.getUserIdentifer(), sid);
        }

        String g_user = (String) httpSession.getAttribute(SessionHolder.G_USER);
        if (StringUtils.isBlank(g_user)) {
            Long userId = Long.parseLong(SessionHolder.getUserIdentifer());
            UserDTO userDTO = null;
            if (SessionHolder.getSessionIDStore().equals(SessionConstants.SESSION_STORE)) {
                userDTO = userService.loadBackEndUser(userId);
            } else {
                userDTO = userService.loadBackEndUser(userId);
            }
            // 将用户信息缓存起来
            httpSession.setAttribute(SessionHolder.G_USER, JSON.toJSONString(userDTO));
        }

        SessionHolder.setSession(httpSession);
        SessionHolder.setRequest(request);
        filterChain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if (StringUtils.isNotBlank(SessionHolder.getUserIdentifer())) {
            return false;
        }
        return true;
    }
}
